<template>
  <div class="main_all">
    <div class="main_left">
      <div class="main_zjsy nowrap" :class="{main_zjsyhover:showactive===1}" @click="getchange(1)">
        <img src="~@/assets/img/01.png">
        <span>最近使用的案件</span>
      </div>
      <div class="main_zjsy nowrap" :class="{main_zjsyhover:showactive===2}" @click="getchange(2)">
        <img src="~@/assets/img/02.png">
        <span>下载新案件</span>
      </div>
      <div class="main_zjsy nowrap" @click="getchange(3)">
        <img src="~@/assets/img/03.png">
        <span>打开本地</span>
      </div>
      <div v-if="skin.app.showAjdj" class="main_zjsy nowrap" :class="{main_zjsyhover:showactive===4}"
           @click="getchange(4)">
        <img src="~@/assets/img/ajdj/01.png">
        <span>案件登记</span>
      </div>
    </div>
    <div class="main_line"></div>
    <div class="main_right">
      <div class="main_rightonetitle nowrap">
        {{ showactive === 1 ? '最近使用的案件' : '' }} {{ showactive === 2 ? '下载新案件' : '' }} {{
          showactive === 4 ? '案件登记' :
            ''
        }}
        {{ showactive === 5 ? '测试' : '' }}
      </div>
      <div v-if="showactive===1" class="main_gdt">
        <div class="main_rightonenr" v-for="(item,index) in recentFiles" @click="showValidModal(item.path)">
          <div class="new_pagenrdiv" @click.stop="removestore(item)" title="关闭"></div>
          <img src="~@/assets/img/caseIco.png">
          <div class="new_pagenrone">
            <span class="new_pagespan nowrap"
                  :title="(item.path ? item.path.split('\\')[item.path.split('\\').length - 1] : '')">{{
                item.path ? item.path.split('\\')[item.path.split('\\').length - 1] : ''
              }}</span>
            <span class="new_pagespan1 nowrap"
                  :title="(item.path ? item.path.replace(/\\/g, '>>') : '')">{{
                item.path ? item.path.replace(/\\/g, '>>') : ''
              }}</span>
          </div>
        </div>
      </div>
      <div v-if="showactive===2" class="download_new_case">
        <div class="userlogin_box">
          <user-login @confirm="showDownload" v-model="userInfo" :show-cancel="false"></user-login>
        </div>
      </div>

      <case-register v-if="showactive==4" style="height:calc(100% - 70px)"></case-register>

    </div>
    <!-- 用户验证 -->
    <vmodal :modalshow="showValidateModal" modaltitle="用户验证" :closeonclickmodal="false"
            :styleobj="{width:'400px',height:'270px',background: 'white'}" @hide="closeUserLogin">
      <div slot="modal" style="padding: 0 40px;">
        <user-login @cancel="closeUserLogin" @confirm="confirm" v-model="userInfo"
                    :disable="[true,true]"></user-login>
      </div>
    </vmodal>
    <!-- 下载弹出框 -->
    <vmodal :modalshow="showDownloadModal" modaltitle="案件下载" :closeonclickmodal="false"
            :styleobj="{width:'1000px',height:'calc(100% - 250px)'}" @hide="showDownloadModal=false">
      <div slot="modal" style="width: 100%;height: 100%;">
        <case-download @selected="openDownloadDetail"></case-download>
      </div>
    </vmodal>
    <!-- 卷宗树 -->
    <vmodal :modalshow="showDownloadDetailModal" modaltitle="案件下载" :closeonclickmodal="false"
            :styleobj="{width:'650px',height:'450px'}" @hide="showDownloadDetailModal=false;showDownloadModal=true">
      <div slot="modal" style="width: 100%;height: 100%;position: relative !important;">
        <download-detail :selected-case="selectedCase" @hide="showDownloadDetailModal = false;
                         showDownloadModal=true"></download-detail>
      </div>
    </vmodal>
  </div>
</template>

<script>
import A from '../common/typeActions'
import {mapState} from 'vuex'
import M from '../common/typeMutations'
import L from '../common/localStore'
import ICE from '../common/ICEHelper'
import SQLite from '../common/SQLiteHelper'
import {action} from '@/common/quantity'
import UserLogin from "@/components/UserLogin";

import crypto from 'crypto'
import javaConnector from "@/plugins/javaConnector";

const sm3 = require('sm3')
const fs = require('fs')

const skin = require('../config/skin')

export default {
  components: {UserLogin},
  name: 'MainPage',
  data() {
    return {
      selectedCase: null,
      showDownloadDetailModal: false, // 卷宗选择树
      showDownloadModal: false, // 案件下载模态框
      showValidateModal: false, // 用户验证模态框
      showactive: 1,

      userPsd: '',

      casePath: '',

      skin: skin[skin.useSkin],

      userInfo: {
        unit: {},
        username: '',
        password: ''
      }
    }
  },
  async mounted() {
    await this.$store.dispatch(A.MAINPAGE.initMainPage)
  },
  computed: {
    ...mapState({
      recentFiles: state => state.mainPage.recentFiles,
      userTree: state => state.common.userTree
    })
  },
  methods: {
    // openWin() {
    //   // SlideEditor
    //   this.$Win.openWin({
    //     windowConfig: {
    //       router:'/SlideEditor'
    //     }
    //   })
    // },
    openDownloadDetail(selectedCase) {
      this.selectedCase = selectedCase
      this.showDownloadModal = false
      this.showDownloadDetailModal = true
    },
    // 显示登陆框，校验
    async showValidModal(filePath) {
      try {
        if (!fs.existsSync(filePath)) {
          try {
            await this.$confirm('案件不存在，是否从最近使用案件列表移除？', '提示')
            let file = this.recentFiles.find(item => item.path === filePath)
            if (file) this.removestore(file)
          } finally {

          }
          return
        }

        if (!await this.$store.dispatch(A.COMMON.UpdateDBFile, filePath)) {
          return
        }

        this.casePath = filePath
        this.loadStatus({loading: true, loadingText: '案件读取中...'})
        // 读取用户信息
        let userInfo = (await SQLite.GetLoginUserInfo(filePath))[0]

        this.userInfo.unit = {
          DWBM: userInfo.unitCode,
          DWMC: userInfo.unitName
        }
        this.userInfo.username = userInfo.userName
        this.userInfo.password = ''

        this.userPsd = userInfo.userPsd

        this.showValidateModal = true
      } catch (err) {
        console.log(err)
        this.$alert(err.message, '提示', {type: 'warning'})
      } finally {
        this.loadStatus({loading: false})
      }
    },
    closeUserLogin() {
      this.userInfo.username = ''
      this.userInfo.unit.DWMC = ''
      this.userInfo.unit.DWBM = ''
      this.userInfo.password = ''

      this.showValidateModal = false
    },
    async confirm() {
      try {
        event.target.blur()
        this.loadStatus({
          loading: true,
          loadingText: '案件加载中，请稍候...'
        })

        if (this.userPsd.toUpperCase() !== crypto.createHash('md5').update(this.userInfo.password).digest('hex').toUpperCase() && this.userPsd.toUpperCase() !== sm3(this.userInfo.password).toUpperCase()) return this.$alert('密码错误', '错误', {type: 'error'})
        // if (this.userPsd.toUpperCase() !== crypto.createHash('md5').update(this.userInfo.password).digest('hex').toUpperCase()) return this.$alert('密码错误', '错误', { type: 'error' })

        this.closeUserLogin()
        this.$store.commit(M.MAINPAGE.SET_USERINFO, {
          unitCode: this.userInfo.unit.DWBM,
          unitName: this.userInfo.unit.DWMC,
          userName: this.userInfo.username
        })

        await this.openCase(this.casePath)
      } catch (e) {
        console.error(e)
      } finally {
        this.loadStatus({loading: false})
      }
    },

    // 下载新案件
    async showDownload() {
      try {
        // 加载动画
        this.loadStatus({loading: true, loadingText: '登录中，请稍候...'})

        if (!this.userInfo.unit.DWBM) return this.$alert('请选择单位！', '错误', {type: 'error'})
        if (!this.userInfo.username) return this.$alert('请输入用户名！', '错误', {type: 'error'})
        if (!this.userInfo.password) return this.$alert('请输入密码！', '错误', {type: 'error'})

        let userInfo = await ICE.GetLoginUserInfo({
          UnitCode: this.userInfo.unit.DWBM,
          UnitName: this.userInfo.unit.DWMC,
          UserName: this.userInfo.username,
          Password: this.userInfo.password
        })
        let saveUserInfo = {
          unitCode: this.userInfo.unit.DWBM,
          unitName: this.userInfo.unit.DWMC,
          userName: userInfo.MC,
          GH: userInfo.GH,
          Password: userInfo.KL
        }
        L.LocalStore.saveRecentlyUser(saveUserInfo)
        this.$store.commit(M.MAINPAGE.SET_USERINFO, saveUserInfo)
        this.userInfo.password = ''
        // 显示下载列表
        this.showDownloadModal = true
      } catch (e) {
        console.error(e)
        this.$alert(e.message || e.InnerException.message, '错误', {
          type: 'error'
        })
      } finally {
        this.loadStatus({loading: false})
      }
    },
    async getchange(v) {
      if (v !== 3) {
        if (v === 2) {
          try {
            this.loadStatus({loading: true, loadingText: '正在加载单位信息，请稍候...'})

            await this.$store.dispatch(action.common.setUserTree)
            this.loadStatus({loading: true, loadingText: '正在加载用户信息，请稍候...'})
            // 最近登陆用户信息
            let userInfo = L.LocalStore.getRecentlyUser() || {}

            this.userInfo.unit = {
              DWBM: userInfo.unitCode,
              DWMC: userInfo.unitName
            }
            this.userInfo.username = userInfo.userName
          } catch (e) {
            console.error(e)
          } finally {
            this.loadStatus({loading: false})
          }
        }
        this.showactive = v
        return
      }
      let res = javaConnector.showOpenDialog({
        defaultPath: "",
        title: '选择本地按键',
        openFile: true,
        openDirectory: true,
        multiSelections: true,
        showHiddenFiles: true,
        filters: [{name: 'Case', extensions: ['case']}]
      })

      console.log(res)
      // let self = this
      // const {BrowserWindow} = remote
      // let win = BrowserWindow.getFocusedWindow()
      // // console.log(win)
      //
      // // 打开本地
      // let rs = remote.dialog.showOpenDialog(win, {
      //   properties: ['openFile', 'showHiddenFiles'],
      //   filters: [{name: 'Case', extensions: ['case']}]
      // })
      // if (rs) self.showValidModal(rs[0])
    },
    // 删除最近案件
    removestore(item) {
      let result = L.LocalStore.removeInfo(item)
      this.$store.commit(M.MAINPAGE.GET_RECENT_FILES, result)
    }
  }
}
</script>

<style scoped lang="scss">
input:disabled {
  background: #f9fafb;
  /* cursor: not-allowed */
}

.main_gdt::-webkit-scrollbar-thumb {
  background-color: #def2fe;
  border-radius: 4px;
}

/*!*---滚动条大小--*!*/

.main_gdt::-webkit-scrollbar {
  width: 2px;
  height: 10px;
}

.main_gdt {
  width: 500px;
  height: calc(100% - 93px);
  /*float: left;*/
  overflow: auto;
}

.download_new_case {
  width: 100%;
  height: calc(100% - 90px);
  position: relative;

  .userlogin_box {
    width: 350px;
  }
}

.main_all {
  width: 100%;
  height: 100%;
  padding: 22px;
  background: white;
  font-family: 微软雅黑;
  font-size: 0;
}

.main_left {
  width: 30%;
  height: 100%;
  overflow: hidden;
  display: inline-block;

  border: 1px solid #bdd5e6;
  border-right: none;

  padding-top: 70px;
  /*padding-left: 15px;*/
}

.main_line {
  width: 1px;
  height: 100%;
  /*float: left;*/
  background: url("~@/assets/img/line.png") no-repeat;
  background-size: 100% 100%;
  display: inline-block;
  border: 1px solid #bdd5e6;
  border-left: none;
  border-right: none;
}

.main_right {
  width: calc(70% - 1px);
  height: 100%;
  /*float: left;*/
  display: inline-block;

  border: 1px solid #bdd5e6;
  border-left: none;
  position: relative;
  padding: 70px 50px 0 50px;
  overflow: hidden;
  box-sizing: border-box;
  overflow-x: auto;
}

.main_zjsy {
  /*width: calc(100% - 15px);*/
  width: 100%;
  height: 90px;
  padding-left: 15px;
  /*float: right;*/
  /*margin: 10px 0;*/
  min-width: 212px;
  cursor: pointer;
}

.main_zjsy:hover {
  background: #def2fe;
}

.main_zjsy img {
  margin: 30px 10px 20px 20px;
  cursor: inherit;
}

.main_zjsy span {
  font-size: 20px;
  color: #333;
  line-height: 90px;
  vertical-align: top;
  cursor: inherit;
}

.main_zjsyhover {
  background: #def2fe;
}

.main_rightonetitle {
  width: 100%;
  height: 70px;
  line-height: 70px;
  font-size: 30px;
  color: #2877be;
  position: relative;
}

.main_rightonenr {
  width: 100%;
  position: relative;
  cursor: pointer;
  height: 70px;
  margin: 5px 0;
}

.main_rightonenr:hover {
  background: #def2fe;
}

.main_rightonenr img {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translate(0, -50%);
  /*margin: 15px;*/
  width: 40px;
  height: 40px;
  cursor: pointer;
}

.new_pagenrdiv {
  position: absolute;
  background: url("~@/assets/img/del.png");
  cursor: pointer;
  right: 0;
  top: 0;
  background-repeat: no-repeat;
  background-position: center;
}

.main_rightonenr:hover .new_pagenrdiv {
  width: 30px;
  height: 30px;
}

.new_pagenrone {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  left: 70px;
  width: calc(100% - 100px);
}

.new_pagespan {
  display: block;
  width: 100%;
  font-size: 18px;
  color: #333;
  cursor: pointer;
}

.new_pagespan1 {
  display: block;
  width: 100%;
  margin-top: 3px;
  font-size: 16px;
  color: #999;
  cursor: pointer;
}

.modal_centernrone {
  width: 100%;
  position: relative;
  margin-bottom: 18px;
}

.modal_centernrone input {
  cursor: auto;
}

.modal_centernrtwo {
  width: 100%;
  padding-top: 15px;
  text-align: center;
}

.model_foot {
  margin-top: 10px;
}

.modal_centernrinput2 {
  width: calc(100% - 160px);
  height: 32px;
  /* float: left; */
  border: 1px solid #ddd;
  outline-color: #34dfff;
  background: rgba(0, 0, 0, 0);
  color: #999;
  font-size: 16px;
  padding-left: 8px;
  border-radius: 3px;
  margin: 1px 0;
}

.modal_centernrinput1 {
  width: calc(100% - 250px);
  height: 32px;
  /* float: left; */
  border: 1px solid #ddd;
  outline-color: #34dfff;
  background: rgba(0, 0, 0, 0);
  color: #999;
  font-size: 16px;
  border-radius: 3px;
  margin: 1px 0;
  display: inline-block;
  cursor: pointer !important;
}

input.modal_centernrinput1 {
  padding-left: 8px;
  cursor: auto !important;
}

.modal_footone {
  width: 100%;
  height: 60px;
  float: left;
}

.inputmsg {
  margin: 10px;
  position: absolute;
}
</style>
